package com.hoshiicloud.purchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.purchase.Po;
import com.hoshiicloud.purchase.feign.IdGeneratorService;
import com.hoshiicloud.purchase.feign.UserService;
import com.hoshiicloud.purchase.mapper.PoMapper;
import com.hoshiicloud.purchase.service.PoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-05-15
 */
@Slf4j
@Service
public class PoServiceImpl extends ServiceImpl<PoMapper, Po> implements PoService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private UserService userService;

    /**
     * @Author:campchen
     * @Description:
     * @Date:上午 10:45 2019/6/14
     * @Param:
     * @return:
     */
    @Cacheable(cacheNames = "Po",key ="#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "后台用户操作-根据供应商与采购单状态进行分页查询")
    public IPage<Po> getPage(IPage<Po> page, QueryWrapper<Po> queryWrapper,String key) {
       return baseMapper.selectPage(page, queryWrapper);
    }


    /**
     * @param id
     * @return com.hoshiicloud.purchase.Po
     * @description: 根据id查询
     */
    @Override
    @Cacheable(cacheNames = "Po", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "采购- -查询 ")
    public Po getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Po getByCode(String code) {
        Wrapper<Po> wrapper = Wrappers.<Po>query().lambda().eq(Po::getPoNo, code);
        return baseMapper.selectOne(wrapper);
    }




    /**
     * @param entity
     * @return boolean
     * @description: 新增
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Po", allEntries = true)
    @Logable(authName = "采购--新增")
    public String savePo(Po entity) {
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败,id生成失败"));
        }
        Response response;
        //订单类型:1-租户采购 2-租户供应商 3-平台采购 4-平台供应商 5-店铺采购 6-店铺供应商
        switch (entity.getSource()) {
            case 2:
                response = userService.getComOrganizationById(entity.getVendorId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,租户供应商信息有误"));
                }
            case 1:
                response= userService.getCompanyById(entity.getCompanyId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,公司信息有误"));
                }
                break;
            case 4:
                response = userService.getPlatOrganizationById(entity.getVendorId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,平台供应商信息有误"));
                }
            case 3:
                response =userService.getPlatformById(entity.getPlatformId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,平台信息有误"));
                }
                response= userService.getCompanyById(entity.getCompanyId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,公司信息有误"));
                }
                break;
            case 6:
                response = userService.getStoreOrganizationById(entity.getVendorId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,店铺供应商信息有误"));
                }
                response = userService.getPlatOrganizationById(entity.getVendorId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,平台供应商信息有误"));
                }
                response= userService.getCompanyById(entity.getCompanyId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,公司信息有误"));
                }
            case 5:
                response = userService.getPlatStoreById(entity.getStoreId());
                if (null == response || response.getCode() != 200 || response.getData() == null) {
                    throw new ServiceException(CommonError.error("新增失败,平台店铺信息有误"));
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + entity.getSource());
        }
        int num = 1;
        boolean flag = true;
        String code =null;
        UidGenerate4C idWorker = new UidGenerate4C(num);
        try {
            while (flag) {
                code = String.valueOf(idWorker.getNextId()).substring(7, 17);
                num++;
                Po po =getByCode(code);
                if (po == null || "".equals(po)) {
                    flag = false;
                }
                if (num > 1000) {
                    throw new ServiceException(CommonError.error("com.hoshiicloud.purchase.service.impl 编码生成重复1000次，请联系管理员！"));
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        entity.setPoNo(code);
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setPoDate(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Po", allEntries = true)
    @Logable(authName = "采购--新增")
    public boolean updateById(Po entity) {
        return this.updateById(entity);
    }


}
